<template>
  <NavBar :title="isLogin ? '登录' : '注册'"></NavBar>
  <div class="login-wrapper">
    <img :src="logo" class="logo" />
    <van-form @submit="onSubmit">
      <van-field
        label="手机号"
        name="loginName"
        placeholder="手机号"
        v-model.trim="userForm.loginName"
        :rules="[
          { required: true, message: '手机号是必填项' },
          { pattern: /^1\d{10}$/, message: '手机号格式错误' }
        ]"
      />
      <van-field
        label="密码"
        placeholder="密码"
        type="password"
        name="password"
        v-model.trim="userForm.password"
        :rules="[{ required: true, message: '密码是必填项' }]"
      />
      <van-field
        label="验证码"
        name="captcha"
        v-model.trim="userForm.captcha"
        :rules="[{validator:validatorCaptcha,message:'验证码输入错误'}]"
      >
       <template #button>
        <Captcha ref="captchaRef" v-model:text="captchaText" :width="120" :height="40"></Captcha>
       </template>
      </van-field>
      <a class="text" @click="changLoginStatus">
        {{ isLogin ? `还没有账号，请点击注册` : '已有账号，请点此登录' }}
      </a>
      <div style="margin: 16px">
        <van-button round block color="#1BAEAE" native-type="submit"> 提交 </van-button>
      </div>
    </van-form>
  </div>
</template>
<script setup>
import logo from '../assets/images/app-logo.png'
import { userRegister, userLogin } from '@/api/user'
import {setLocal} from '@/utils';
const { proxy } = getCurrentInstance()
const route = useRoute();
const router = useRouter();
const userForm = reactive({
  loginName: '',
  password: '',
  captcha:''
})
const captchaText = ref('');
const captchaRef = ref(null);
const isLogin = ref(true)
const changLoginStatus = () => {
  userForm.loginName = ''
  userForm.password = ''
  isLogin.value = !isLogin.value
}
function validatorCaptcha(){
  // 验证用户输入的内容和验证码中的内容是否相同
  if(userForm.captcha === captchaText.value){
    return true;
  }
  //如果说验证码不正确，则重新刷新验证码
  captchaRef.value.reset();
  return false;
}
async function onSubmit() {
  try {
    //说明当时是在登录
    if (isLogin.value) {
      //登录成功后会返回一个token
      let token = await userLogin(userForm)
      setLocal('token',token);
      proxy.$showToast('恭喜登录成功')
      //当登录成功后要跳转路径
      let {redirect} = route.query;
      //如果有redirect的话，说明本来是准备访问redirect路径的，因为没有登录才跳过来
      //所以等登录成功后还要跳回去
      if(redirect){
        delete route.query.redirect;
        //替换当前路径，而不是在历史栈中添加一个新的条目
        router.replace({
            path:redirect,
            query:route.query
        });
      }else{
        router.push('/');
      }
    } else {
      //当前在注册
      await userRegister(userForm)
      proxy.$showToast('恭喜注册成功，快去登录吧')
      changLoginStatus()
    }
  } catch (error) {
    proxy.$showToast((isLogin.value ? '登录' : '注册') + '失败:'+error.message)
    console.log(error)
  }
}
</script>
<style lang="less">
.login-wrapper {
  padding: 20px;
  .logo {
    display: block;
    margin: 75px auto 20px;
    width: 140px;
    height: 140px;
  }
  .text {
    display: inline-block;
    margin: 20px 0px;
    padding: 0 15px;
    color: @primary-color;
    font-size: 14px;
  }
}
</style>
